#include "StdAfx.h"
#include "SwarmEmitter.h"

#include "../Kernel.h"

extern Kernel* g_kernel;

#define TIME (g_kernel->GetTime())

const float PI = 3.14159265358979323846f;
#define random()	((rand () & 0x7fff) / ((float)0x7fff))
#define crandom()	(2.0 * (random() - 0.5))


SwarmEmitter::SwarmEmitter(void)
{
}

SwarmEmitter::~SwarmEmitter(void)
{
}

/** Update the Emitters */
void SwarmEmitter::Update(long dt)
{
    ClearDead();
    float deltaTime = g_kernel->GetFrameTime()/ 1000.0f;
    type_Particles::iterator it = m_particles.begin();
    for(; it!=m_particles.end(); it++)
    {
        Particle &p = *it;

        // kill the particle
        if ( TIME > p.lifeTime )
        {
            p.isDead = true;
            continue;
        }

		// decreate the alpha value
        if ( TIME > p.nextAlphaUpdate)
        {
            p.alpha -= 0.1f; 
            p.nextAlphaUpdate = TIME + p.fadeTime;
        }

		p.position = p.position + Vector2f(crandom()*4,crandom()*4);

        Vector3f color = EndColor - p.color;
        Vector3f fade  = color * ColorFadeTime;
        p.color = p.color + fade;
        
    }

    if ( (m_particles.size() < MaxParticles) && TIME > m_spawnTimer && MaxTotalParticles >= m_particlesCreated )
    {
        Spawn();
        m_spawnTimer = TIME + SpawnRate;

    }

}

/** Render the Emitters */
void SwarmEmitter::Render(IRender* r, ICamera* cam )
{
    type_Particles::iterator it = m_particles.begin();
    for(; it!=m_particles.end(); it++)
    {
        r->SetColor( it->color.GetX(), it->color.GetY(), it->color.GetZ(), it->alpha  );

        Vector2f position( it->position - cam->GetPosition() );
		
		r->FillCircle(it->size ,position.x,position.y);
    }
}

void SwarmEmitter::Spawn()
{
    Particle p;
    p.color    = StartColor;

    CalculateJitter( p, InitVel );
    p.fadeTime = AlphaFadeTime;
    p.position = Position;
    // p.velocity = InitVel;
    p.lifeTime = TIME + LifeSpan;

    p.acceleration = Acceleration;
    p.alpha = StartAlpha;
    p.size = ParticleSize;

    m_particlesCreated++;
    m_particles.push_back( p );

}